#include<iostream>
#include"DealRet.h"
#include<thread>

std::atomic_flag DealRet::lock_sts = ATOMIC_FLAG_INIT;

std::unordered_map<int, std::shared_ptr<Ret>> DealRet::STS;

void DealRet::dealRet(int fd){
  auto &&ret = getRet(fd);
  ret->send(fd);
  if(ret->over)
    eraseRet(fd);
}

void DealRet::addRet(std::shared_ptr<Ret> &ret, int fd){
  while(lock_sts.test_and_set()) std::this_thread::yield();
  STS[fd] = ret;
  lock_sts.clear();
}

void DealRet::eraseRet(int fd){
  while(lock_sts.test_and_set()) std::this_thread::yield();
  STS.erase(fd);
  lock_sts.clear();
}

std::shared_ptr<Ret> DealRet::getRet(int fd){
  std::shared_ptr<Ret> ret;
  while(lock_sts.test_and_set()) std::this_thread::yield();
  if(STS.find(fd) != STS.end())
    ret = STS[fd];
  lock_sts.clear();
  return ret;
}
